﻿using Kinlo.Entitys;
using Kinlo.MESDocking;
using MaterialDesignThemes.Wpf;
using Microsoft.VisualBasic.Devices;
using Microsoft.Win32;
using NewLife.Data;
using SkiaSharp;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.DirectoryServices;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using UIWindows.Commands;
using UIWindows.Domains;
using UIWindows.Enums;
using UIWindows.GlobalStatics;
using UIWindows.Models;
using UIWindows.Models.ParameterModels;
using UIWindows.Tools.Helper;
using UIWindows.UserControls;
using UIWindows.Views;
using UIWindows.Views.Dialogs;
using XCode;
using XingLucifer.IBase.Enums;

namespace UIWindows.ViewModels
{
    public class SupplementaryDataViewModel : ViewModelBase
    {
        public AsyncObservableCollection<ImportExcelModel> ImportExcels { get; set; }
        public AsyncObservableCollection<ProductionData> WeightList { get; set; }
        private double _netWeight;

        public double NetWeight
        {
            get { return _netWeight; }
            set { SetProperty(ref _netWeight, value); }
        }

        private double _outputWeight;

        public double OutputWeight
        {
            get { return _outputWeight; }
            set { SetProperty(ref _outputWeight, value); }
        }

        private GridView _productionDataView;

        public GridView ProductionDataView
        {
            get { return _productionDataView; }
            set { SetProperty(ref _productionDataView, value); }
        }


        public DisplayItemsStatic _displayItems;
        protected ParameterStatic _parameterStatic;
        protected TemporaryStatic _temporaryStatic;
        SnowflakeManager _snowflake;
        /// <summary>
        /// 间隔时间
        /// </summary>
        public int Intervals { get; set; } = 100;
        public SupplementaryDataViewModel(DisplayItemsStatic displayItems, ParameterStatic parameterStatic, TemporaryStatic temporaryStatic)
        {
            _snowflake = new SnowflakeManager(12);
            WeightList = new AsyncObservableCollection<ProductionData>();
            ImportExcels = new AsyncObservableCollection<ImportExcelModel>();
            ProductionDataView = new GridView();
            _displayItems = displayItems;
            _parameterStatic = parameterStatic;
            _temporaryStatic = temporaryStatic;
            Load();
        }

        public DelegateCommand ImportExcelCMD => new DelegateCommand(() =>
        {
            try
            {
                Task.Run(() =>
                {
                    OpenFileDialog dialog = new OpenFileDialog();
                    dialog.Multiselect = false;//该值确定是否可以选择多个文件
                    dialog.Title = "请选择文件";
                    dialog.Filter = "Excel 工作簿(*.xls)|*.xls";
                    var v = dialog.ShowDialog();
                    if (v == true)
                    {
                        string filePath = dialog.FileName;
                        var excelResult = ExportHelper.ImproExcel<ImportExcelModel>(filePath);
                        ImportExcels = new AsyncObservableCollection<ImportExcelModel>(excelResult);
                    }
                });
            }
            catch (Exception)
            {


            }
        });

        public DelegateCommand RestoreDataCMD => new DelegateCommand(() =>
        {
            try
            {
                Task.Run(() =>
                {
                    RunLog("恢复数据开始");

                    DateTime startTime = DateTime.Now.AddDays(-12);
                    long startTimeLong = SnowflakeManager.GetTimeId(startTime);
                    long endTimeLong = SnowflakeManager.GetTimeId(DateTime.Now.AddDays(-10));
                    ProductionData.Meta.TableName = $"ProductionData_{startTime:yyyy}{startTime.GetQuarterly()}";
                    XCode.Expression expression = ProductionData._.SnowflakeId >= startTimeLong & ProductionData._.SnowflakeId <= endTimeLong & ProductionData._.ResultTotal == 1;
                    var list = ProductionData.FindAll(expression);

                    if (list.Count == 0)
                    {
                        RunLog("参考数据数量为0，退出！");
                        return;
                    }
                    //二注取从其它设备取 电池干重及一注下料重量
                    MySqlHelper mySqlHelper = new MySqlHelper(_parameterStatic.MESParameter.OthenDatabaseurl);
                    foreach (var excel in ImportExcels)
                    {
                        int indexRandow = new Random().Next(0, list.Count - 1);
                        var oneData = mySqlHelper.GetBatteryByCode(excel.Barcode);
                        if (oneData.status)
                        {
                            RunLog($"条码：{excel.Barcode}取一注数据成功!");
                            WeightList.Add(CreateBattery(excel.Barcode,
                                oneData.netWeight < 10 ? NetWeight : oneData.netWeight,
                                oneData.outputWeight < 10 ? OutputWeight : oneData.outputWeight, list[indexRandow]));
                        }
                        else
                        {
                            RunLog($"条码：{excel.Barcode}取一注数据失败!");
                            WeightList.Add(CreateBattery(excel.Barcode, NetWeight, OutputWeight, list[indexRandow]));
                        }
                    }
                    RunLog("恢复数据完成");
                });
            }
            catch (Exception ex)
            {

                RunLog($"恢复数据异常：{ex}");
            }



        });

        public DelegateCommand SaveDataCMD => new DelegateCommand(() =>
        {
            Task.Run(() =>
            {
                int count = 0;
                RunLog("开始插入数据库");
                ProductionData.Meta.TableName = $"ProductionData_{DateTime.Now:yyyy}{DateTime.Now.GetQuarterly()}";
                WeightList.ToList().ForEach(entity =>
                {
                    for (int i = 0; i < 3; i++)
                    {
                        try
                        {
                            count += entity.Insert();
                            //entity.Items.Add("TableName", ProductionData.Meta.TableName);                        
                            RunLog($" ID:[{entity.SnowflakeId}]对应的条码为:[{entity.BarCode}] 插入数据库成功");
                            break;
                        }
                        catch (Exception ex)
                        {
                            RunLog($" ID:[{entity.SnowflakeId}]对应的条码为:[{entity.BarCode}] 第[{i}]次 保存数据库失败：{ex}");
                            Thread.Sleep(500);
                        }
                    }

                });
                if (count == WeightList.Count)
                    RunLog($"待插入数据{WeightList.Count}条，实际插入数据库{count}条，保存成功！");
                else
                    RunLog($"待插入数据{WeightList.Count}条，实际插入数据库{count}条，部分保存失败s！", MessageLevelType.警告);
            });
        });

        
        /// <summary>
        /// 按条码上传送MES出站
        /// </summary>
        public DelegateCommand BarcodeToUpdateOutputMES => new DelegateCommand(async () =>
        {
            await Task.Run(() =>
            {
                
            });
        });
        public DelegateCommand<ListView> SelectUpdata => new DelegateCommand<ListView>(async sender =>
        {
            if (sender.SelectedItems.Count == 0)
            {
                return;
            }
            _ = DialogHost.Show(new LoadingDialogs(), PopUpTypes.Global.ToString()).ConfigureAwait(false);

            await Task.Run(() =>
            {
                
            });
        });
        public DelegateCommand<ListView> SelectInputAndOutputUpdata => new DelegateCommand<ListView>(async sender =>
        {
            if (sender.SelectedItems.Count == 0)
            {
                return;
            }
            _ = DialogHost.Show(new LoadingDialogs(), PopUpTypes.Global.ToString()).ConfigureAwait(false);

            await Task.Run(() =>
            {
               

            });
        });
        /// <summary>
        /// 创建电池
        /// </summary>
        /// <param name="barcode"></param>
        /// <param name="netWeight"></param>
        /// <param name="outputWeight"></param>
        /// <param name="production"></param>
        /// <returns></returns>
        ProductionData CreateBattery(string barcode, double netWeight, double outputWeight, ProductionData production)
        {

            RunLog($"条码：{barcode}创建开始，干重：{netWeight},下料重：{outputWeight}!");
            var off = new Random().Next(-200, 200) / 100.00;
            var off2 = new Random().Next(-20, 20) / 100.00;
            var timeRandom = new Random().Next(8, 15);
            var entity = new ProductionData
            {
                SnowflakeId = _snowflake.NextId(),
                BarCode = barcode,
                TimeScanCodeBefore = DateTime.Now.AddDays(-timeRandom).GetJSTimeUtc(),
                RangeAfterWeighing = $"{_parameterStatic.RangeParameter.WeighAfterDown}-{_parameterStatic.RangeParameter.WeighAfterUp}",
                RangeForeweigh = $"{_parameterStatic.RangeParameter.WeighBeforeDown}-{_parameterStatic.RangeParameter.WeighBeforeUp}",
                RangeFluidRate = $"{_parameterStatic.RangeParameter.QuantitativeDown}-{_parameterStatic.RangeParameter.Quantitative}-{_parameterStatic.RangeParameter.QuantitativeUp}",
                BatchElectrolyte = _parameterStatic.CollectionItemsParameter.BatchElectrolyte,
                ProductType = _parameterStatic.CollectionItemsParameter.ProductType.ToString(),
                GlueNailBatch = _parameterStatic.CollectionItemsParameter.GlueNailBatch,
                EquipNum = _parameterStatic.CollectionItemsParameter.EquipNum,
                ProductionLineNo = _parameterStatic.CollectionItemsParameter.ProductionLineNo,
                Operator = _temporaryStatic.Mes_Account,
                ResultTotal = ResultTypes.合格,
                ResultScanCodeBefore = ResultTypes.合格,
                LocationScanCodeBefore = (byte)1,
                WorkOrderNumber = _parameterStatic.CollectionItemsParameter.WorkOrder,
                ResultOutput = ResultTypes._,
                NetWeight = netWeight,
                FormerWeighing = outputWeight + off2,
                OneAfterWeighing = outputWeight,
                AfterWeighing = netWeight + _parameterStatic.RangeParameter.Quantitative + off,

            };
            entity.TargetInjectionVolume = _parameterStatic.RangeParameter.Quantitative - (entity.FormerWeighing - entity.NetWeight);
            entity.ActualInjectionVolume = Math.Round(entity.AfterWeighing - entity.FormerWeighing, 2, MidpointRounding.AwayFromZero);
            entity.InjectionVolumeDeviationValue = Math.Round(entity.ActualInjectionVolume - entity.TargetInjectionVolume, 2, MidpointRounding.AwayFromZero);
            entity.ActualTotalInjectionVolume = Math.Round(entity.AfterWeighing - entity.NetWeight, 2, MidpointRounding.AwayFromZero);
            entity.TotalInjectionVolumeDeviationValue = Math.Round(entity.ActualTotalInjectionVolume - _parameterStatic.RangeParameter.Quantitative, 2, MidpointRounding.AwayFromZero);
            entity.ResultAfterWeighing = ResultTypes.合格;


            entity.LeakVacuum = production.LeakVacuum;
            entity.LeakResult = ResultTypes.合格;
            entity.RowNo = production.RowNo;
            entity.ColunmNo = production.ColunmNo;
            entity.InjectionPumpNo = production.InjectionPumpNo;
            entity.CylinderNo = production.CylinderNo;
            entity.LayerNumber = production.LayerNumber;
            entity.InjectionTime = production.InjectionTime;
            entity.CycleTime = production.CycleTime;
            entity.FillingCup = production.FillingCup;
            entity.CycleNumber = production.CycleNumber;
            entity.InjBeforeVacuum = production.InjBeforeVacuum;
            entity.InjAfterVacuum = production.InjAfterVacuum;
            entity.InjPressure = production.InjPressure;
            entity.CyclicPressurizationValue = production.CyclicPressurizationValue;
            entity.CirculatingVacuumValue = production.CirculatingVacuumValue;
            entity.StationNo = production.StationNo;

            RunLog($"条码：{barcode}创建完成!");
            return entity;

        }

        public void Load()
        {

            ProductionDataView.Columns.Clear();
            List<DisplayItemsModel> list = new List<DisplayItemsModel>(_displayItems.WeighingDisplayItems);
            list.Sort((x, y) => x.CompareTo(y));
            foreach (var item in list)
            {
                if (item.IsDisplay)
                {
                    var gvc = new GridViewColumn()
                    {
                        DisplayMemberBinding = new Binding()
                        {
                            Path = new System.Windows.PropertyPath(item.Name),
                        },
                        Header = item.Description,
                    };
                    switch (item.DataType)
                    {
                        case "浮点型":
                            gvc.DisplayMemberBinding.StringFormat = "F2";
                            break;
                        case "时间型":
                            gvc.DisplayMemberBinding.StringFormat = "yyyy-MM-dd HH:mm:ss";
                            (gvc.DisplayMemberBinding as Binding).Converter = new Tools.Converter.TimeStampToDateTimeStringConverter();
                            break;
                    }
                    ProductionDataView.Columns.Add(gvc);
                }
            }
            _displayItems.IsDataUpdate = false;
        }


        void RunLog(string info, MessageLevelType levelType = MessageLevelType.信息)
        {
            $"[手动恢复数据]：{info}".RunLog(levelType);
        }
    }


}
